package ar.com.ford.it.fullEconomics.persistence.dao.query;

import java.sql.Timestamp;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReportQuery;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese01Economic;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese03Econvalue;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import com.ford.it.persistence.impl.toplink.CustomExpressionFactory;

public class EconomicIndexValuesPeriodFindQuery implements
        CustomExpressionFactory {

    /*
     * SELECT * FROM economicIndex eIndex WHERE <month> - eIndex.updateFrequency > (
     * SELECT MAX(eValue.effDate) FROM economicIndexValue eValue JOIN
     * economicIndex eIndex ON (eValue.economicIndex.pk = eIndex.pk) )
     */

    public Expression createExpression(ExpressionBuilder builder,
            Object[] parameters) {
        Expression exp = null;

        Teese03Econvalue ecoV = (Teese03Econvalue) parameters[0];
        Teese01Economic economic = ecoV.getTeese01Economic();
        Timestamp startDate = ecoV.getEese03EcvalueEffectivDateY();
        // Contendra la fecha limite de busqueda , no aplica el criterio
        // Approval solo se uso el contenedor del obj
        Timestamp finishDate = ecoV.getEese03EcvalueApprovalS();
        String findState = ecoV.getEese03EcvalueaApprovalUserC();
        Teesg01Plant plant = ecoV.getEese03PlantCodeC();
        exp = builder.get("eese03PlantCodeC").equal(
                economic.getEese01PlantCodeC());
        if (findState != null) {
            if ("aprobados".equals(findState))
                exp = exp.and(builder.get("eese03EcvalueApprovalS").notNull());
            if ("registrados".equals(findState))
                exp = exp.and(builder.get("eese03LastUserUpdtC").notNull());
        }
        ReportQuery reportQuery = new ReportQuery(builder);
        reportQuery.setReferenceClass(Teese03Econvalue.class);
        reportQuery.addMaximum("eese03EcvalueEffectivDateY", builder
                .get("eese03EcvalueEffectivDateY"));
        exp = exp.and(builder.get("eese03EcvalueTypeCodeC").equalsIgnoreCase(
                ecoV.getEese03EcvalueTypeCodeC().trim()));
        exp = exp.and(builder.get("teese01Economic").equal(economic));
        exp = exp.and(builder.get("eese03EcvalueEffectivDateY").greaterThan(
                startDate));
        exp = exp.and(builder.get("eese03EcvalueEffectivDateY").lessThan(
                finishDate));
        exp = exp.and(builder.get("eese03EcvalueEffectivDateY").equal(
                builder.subQuery(reportQuery)));

        return exp;
    }

}
